package com.ruoyi.system.service.impl;

import java.util.List;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.TeacherInfoMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.domain.TeacherInfo;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ITeacherInfoService;

/**
 * 教师信息Service业务层处理
 *
 * @author ltr
 * @date 2024-10-21
 */
@Service
public class TeacherInfoServiceImpl implements ITeacherInfoService
{
    private static final Logger log = LoggerFactory.getLogger(TeacherInfoServiceImpl.class);

    @Autowired
    private TeacherInfoMapper teacherInfoMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    protected Validator validator;

    // ==================== 原有功能 ====================

    /**
     * 查询教师信息
     *
     * @param teacherId 教师信息主键
     * @return 教师信息
     */
    @Override
    public TeacherInfo selectTeacherInfoByTeacherId(Long teacherId)
    {
        TeacherInfo teacherInfo = teacherInfoMapper.selectTeacherInfoByTeacherId(teacherId);
        // 填充nickName字段（从sys_user表获取）
        if (teacherInfo != null && teacherInfo.getUserId() != null)
        {
            SysUser user = userMapper.selectUserById(teacherInfo.getUserId());
            if (user != null)
            {
                teacherInfo.setNickName(user.getNickName());
            }
        }
        return teacherInfo;
    }

    /**
     * 根据用户ID查询教师信息
     *
     * @param userId 用户ID
     * @return 教师信息
     */
    @Override
    public TeacherInfo selectTeacherInfoByUserId(Long userId)
    {
        return teacherInfoMapper.selectTeacherInfoByUserId(userId);
    }

    /**
     * 查询教师信息列表
     *
     * @param teacherInfo 教师信息
     * @return 教师信息
     */
    @Override
    public List<TeacherInfo> selectTeacherInfoList(TeacherInfo teacherInfo)
    {
        List<TeacherInfo> list = teacherInfoMapper.selectTeacherInfoList(teacherInfo);
        // 填充nickName字段（从sys_user表获取）
        for (TeacherInfo info : list)
        {
            if (info.getUserId() != null)
            {
                SysUser user = userMapper.selectUserById(info.getUserId());
                if (user != null)
                {
                    info.setNickName(user.getNickName());
                }
            }
        }
        return list;
    }

    /**
     * 新增教师信息
     *
     * @param teacherInfo 教师信息
     * @return 结果
     */
    @Override
    public int insertTeacherInfo(TeacherInfo teacherInfo)
    {
        teacherInfo.setCreateTime(DateUtils.getNowDate());
        return teacherInfoMapper.insertTeacherInfo(teacherInfo);
    }

    /**
     * 修改教师信息
     *
     * @param teacherInfo 教师信息
     * @return 结果
     */
    @Override
    public int updateTeacherInfo(TeacherInfo teacherInfo)
    {
        teacherInfo.setUpdateTime(DateUtils.getNowDate());

        // 同步更新系统用户的昵称和邮箱
        if (teacherInfo.getUserId() != null)
        {
            SysUser user = new SysUser();
            user.setUserId(teacherInfo.getUserId());

            // 更新昵称
            if (StringUtils.isNotEmpty(teacherInfo.getNickName()))
            {
                user.setNickName(teacherInfo.getNickName());
            }

            // 更新邮箱
            if (StringUtils.isNotEmpty(teacherInfo.getEmail()))
            {
                user.setEmail(teacherInfo.getEmail());
            }

            userMapper.updateUser(user);
        }

        return teacherInfoMapper.updateTeacherInfo(teacherInfo);
    }

    /**
     * 批量删除教师信息
     *
     * @param teacherIds 需要删除的教师信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTeacherInfoByTeacherIds(Long[] teacherIds)
    {
        // 删除教师信息前，先删除关联的系统用户账号
        for (Long teacherId : teacherIds)
        {
            TeacherInfo teacherInfo = teacherInfoMapper.selectTeacherInfoByTeacherId(teacherId);
            if (teacherInfo != null && teacherInfo.getUserId() != null)
            {
                // 检查是否有指导学生
                if (teacherInfo.getCurrentStudents() != null && teacherInfo.getCurrentStudents() > 0)
                {
                    throw new ServiceException("教师【" + teacherInfo.getTeacherNo() + "】仍有指导学生，无法删除");
                }

                // 删除用户角色关联
                userRoleMapper.deleteUserRoleByUserId(teacherInfo.getUserId());
                // 删除系统用户
                userMapper.deleteUserById(teacherInfo.getUserId());
            }
        }

        return teacherInfoMapper.deleteTeacherInfoByTeacherIds(teacherIds);
    }

    /**
     * 删除教师信息信息
     *
     * @param teacherId 教师信息主键
     * @return 结果
     */
    @Override
    public int deleteTeacherInfoByTeacherId(Long teacherId)
    {
        return teacherInfoMapper.deleteTeacherInfoByTeacherId(teacherId);
    }

    /**
     * 保存或更新教师信息
     * 如果该用户已有教师信息则更新，否则插入
     *
     * @param teacherInfo 教师信息
     * @return 结果
     */
    @Override
    public int saveOrUpdateTeacherInfo(TeacherInfo teacherInfo)
    {
        TeacherInfo existingInfo = teacherInfoMapper.selectTeacherInfoByUserId(teacherInfo.getUserId());
        if (existingInfo != null)
        {
            // 已存在，执行更新
            teacherInfo.setTeacherId(existingInfo.getTeacherId());
            return updateTeacherInfo(teacherInfo);
        }
        else
        {
            // 不存在，执行插入
            return insertTeacherInfo(teacherInfo);
        }
    }

    // ==================== 新增：管理员功能 ====================

    /**
     * 新增教师信息并自动创建系统账号
     *
     * @param teacherInfo 教师信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTeacherInfoWithAccount(TeacherInfo teacherInfo)
    {
        // 1. 创建系统用户账号
        SysUser user = createUserAccount(
                teacherInfo.getTeacherNo(),
                teacherInfo.getNickName(),
                teacherInfo.getEmail()
        );



        // 插入用户
        int rows = userMapper.insertUser(user);
        if (rows > 0)
        {
            // 分配教师角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(100L);
            userRoleMapper.batchUserRole(java.util.Arrays.asList(userRole));

            // 2. 创建教师信息，关联用户ID
            teacherInfo.setUserId(user.getUserId());
            teacherInfo.setCreateTime(DateUtils.getNowDate());

            // 设置默认值
            if (teacherInfo.getCurrentStudents() == null)
            {
                teacherInfo.setCurrentStudents(0);
            }
            if (teacherInfo.getMaxStudents() == null)
            {
                teacherInfo.setMaxStudents(8);
            }

            return teacherInfoMapper.insertTeacherInfo(teacherInfo);
        }

        throw new ServiceException("创建教师账号失败");
    }

    /**
     * 校验工号是否唯一
     *
     * @param teacherInfo 教师信息
     * @return 结果
     */
    @Override
    public boolean checkTeacherNoUnique(TeacherInfo teacherInfo)
    {
        Long teacherId = StringUtils.isNull(teacherInfo.getTeacherId()) ? -1L : teacherInfo.getTeacherId();
        TeacherInfo info = teacherInfoMapper.checkTeacherNoUnique(teacherInfo.getTeacherNo());
        if (StringUtils.isNotNull(info) && info.getTeacherId().longValue() != teacherId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入教师信息数据
     *
     * @param teacherList 教师信息数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importTeacherInfo(List<TeacherInfo> teacherList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(teacherList) || teacherList.size() == 0)
        {
            throw new ServiceException("导入教师数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (TeacherInfo teacher : teacherList)
        {
            try
            {
                // 验证是否存在这个教师
                TeacherInfo existTeacher = teacherInfoMapper.checkTeacherNoUnique(teacher.getTeacherNo());

                if (StringUtils.isNull(existTeacher))
                {
                    // 新增教师
                    BeanValidators.validateWithException(validator, teacher);
                    teacher.setCreateBy(operName);
                    insertTeacherInfoWithAccount(teacher);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、工号 " + teacher.getTeacherNo() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    // 更新教师
                    BeanValidators.validateWithException(validator, teacher);
                    teacher.setTeacherId(existTeacher.getTeacherId());
                    teacher.setUserId(existTeacher.getUserId());
                    teacher.setUpdateBy(operName);
                    updateTeacherInfo(teacher);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、工号 " + teacher.getTeacherNo() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、工号 " + teacher.getTeacherNo() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工号 " + teacher.getTeacherNo() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }

    /**
     * 重置教师账号密码
     *
     * @param teacherId 教师ID
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public int resetTeacherPassword(Long teacherId, String operName)
    {
        TeacherInfo teacherInfo = teacherInfoMapper.selectTeacherInfoByTeacherId(teacherId);
        if (teacherInfo == null || teacherInfo.getUserId() == null)
        {
            throw new ServiceException("教师信息不存在或未关联系统账号");
        }

        // 重置密码为123456
        String newPassword = SecurityUtils.encryptPassword("123456");
        return userMapper.resetUserPwd(teacherInfo.getUserId(), newPassword);
    }

    /**
     * 创建系统用户账号
     *
     * @param userName 用户名（工号/学号）
     * @param nickName 昵称前缀
     * @param email 邮箱
     * @return 用户对象
     */
    private SysUser createUserAccount(String userName, String nickName, String email)
    {
        // 检查用户名是否已存在
        SysUser existUser = userMapper.checkUserNameUnique(userName);
        if (existUser != null)
        {
            throw new ServiceException("用户名【" + userName + "】已存在，无法创建账号");
        }

        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setNickName(nickName);

        // 邮箱可以为空
        if (StringUtils.isNotEmpty(email))
        {
            user.setEmail(email);
        }

        // 设置默认密码：123456
        user.setPassword(SecurityUtils.encryptPassword("123456"));

        // 设置默认部门（可根据实际情况调整）
        user.setDeptId(103L); // 若依默认研发部门ID，请根据实际情况修改

        // 设置用户状态为正常
        user.setStatus("0");

        return user;
    }
}